//
//  CNHTTPSessionManager.m
//  BeeQuick_19
//
//  Created by 刘家强 on 16/9/22.
//  Copyright © 2016年 CN Team. All rights reserved.
//

#import "CNHTTPSessionManager.h"

@implementation CNHTTPSessionManager

+ (instancetype)sharedManager {
    
    static CNHTTPSessionManager *_manager;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        // 初始化
        _manager = [CNHTTPSessionManager new];
        
        // 设置BaseURL
        NSURL *url = [NSURL URLWithString:@"http://iosapi.itcast.cn/loveBeen/"];
        _manager = [[CNHTTPSessionManager alloc]initWithBaseURL:url];
        
        // 设置请求方式
        _manager.requestSerializer = [[AFJSONRequestSerializer alloc]init];
        _manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    });
    return _manager;
}

- (void)request:(CNHttpMethod)method componentUrlString:(NSString *)urlString parameters:(id)parameters completion:(void(^)(id response, NSError *error))completion {
    
    // 请求成功的block
    void(^successBlock)(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) = ^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        // 请求成功
        completion(responseObject, nil);
    };
    
    // 请求失败的block
    void(^failureBlock)(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) = ^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        // 请求失败
        completion(nil, error);
        NSLog(@"请求错误%@", error);
    };
    
    if (method == CNHttpMethodGet) {
        [self GET:urlString parameters:parameters progress:nil success:successBlock failure:failureBlock];
    }else{
        // 发送post请求
        [self POST:urlString parameters:parameters progress:nil success:successBlock failure:failureBlock];
    }
    
}

@end
